from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from .serializers import LabelsModelSerializer, QuestionModelSerializer, \
    QuestionDetialSerializer, ReplyModelSerializer, QuestionCreateModelSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from apps.user.utils import JwtAuthentication
from apps.user.models import User
from .models import Label, Question, Reply
from django_redis import get_redis_connection


class LabelsListAPIView(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelsModelSerializer


class LabelRetrieveAPIView(RetrieveAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelsModelSerializer


class LabelFocusAPIView(UpdateAPIView):
    authentication_classes = [JwtAuthentication]

    def update(self, request, *args, **kwargs):
        user = request.user
        user = User.objects.get(id=user["user_id"])
        pk = self.kwargs.get("pk")
        keyword = self.kwargs.get("keyword")
        instance = Label.objects.get(pk=pk)
        if keyword == "focusin":
            instance.users.add(user)
            instance.save()
            return Response({"success": True, "message": "添加关注成功"})
        if keyword == "focusout":
            instance.users.remove(user)
            instance.save()
            return Response({"success": True, "message": "取消关注成功"})
        else:
            return Response(status=HTTP_400_BAD_REQUEST)


class LabelUsersAPIView(ListAPIView):
    authentication_classes = [JwtAuthentication]

    def get_queryset(self):
        user = self.request.user
        return Label.objects.filter(users__id=user['user_id'])

    serializer_class = LabelsModelSerializer


class LabelQuestionsAPIView(ListAPIView):
    def get_queryset(self):
        label_id = int(self.kwargs.get("label_id"))
        keyword = self.kwargs.get("keyword")
        if keyword == "new":
            keyword = "-createtime"
            queryset = Question.objects.all()
        if keyword == "hot":
            keyword = "-reply"
            queryset = Question.objects.all()
        if keyword == "wait":
            keyword = "reply"
            queryset = Question.objects.filter(reply=0)
        if label_id == -1:
            queryset = queryset.order_by(keyword)
        else:
            queryset = queryset.filter(labels__id=label_id).order_by(keyword)
        return queryset

    serializer_class = QuestionModelSerializer


class QuestionsAPIView(CreateAPIView):
    authentication_classes = [JwtAuthentication]
    queryset = Question.objects.all()
    serializer_class = QuestionCreateModelSerializer


class QuestionsDetialAPIView(RetrieveAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionDetialSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.visits += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class ReplyModelViewSet(ModelViewSet):
    queryset = Reply.objects.all()
    serializer_class = ReplyModelSerializer


class QuestionUsefulAPIView(UpdateAPIView):
    authentication_classes = [JwtAuthentication]
    queryset = Question.objects.all()
    serializer_class = QuestionModelSerializer

    def update(self, request, *args, **kwargs):
        user_id = request.user["user_id"]
        pk = self.kwargs.get("pk")
        keyword = self.kwargs.get("keyword")
        instance = Question.objects.get(pk=pk)
        redis_coon = get_redis_connection("flags")
        res = redis_coon.get("u%s_q%s" % (user_id, pk))
        if res:
            return Response({"message": "您已经评价过该问题", "success": False})
        else:
            if keyword == "useful":
                instance.useful_count += 1
                redis_coon.setex("u%d_q%d" % (user_id, pk), 7 * 24 * 3600, 1)
            elif keyword == "unuseful":
                instance.unuseful_count += 1
                redis_coon.setex("u%s_q%s" % (user_id, pk), 7 * 24 * 3600, 1)
            else:
                return Response(status=HTTP_400_BAD_REQUEST)
        instance.save()
        return Response({"message": "操作成功", "success": True})


class ReplyUsefulAPIView(APIView):
    authentication_classes = [JwtAuthentication]

    def put(self, request, *args, **kwargs):
        user_id = request.user["user_id"]
        pk = self.kwargs.get("pk")
        keyword = self.kwargs.get("keyword")
        instance = Reply.objects.get(pk=pk)
        redis_coon = get_redis_connection("flags")
        res = redis_coon.get("r%d_q%d" % (user_id, pk))
        if res:
            return Response({"message": "您已经评价过该回答", "success": False})
        else:
            if keyword == "useful":
                instance.useful_count += 1
                redis_coon.setex("r%d_q%d" % (user_id, pk), 7 * 24 * 3600, 1)
            elif keyword == "unuseful":
                instance.unuseful_count += 1
                redis_coon.setex("r%d_q%d" % (user_id, pk), 7 * 24 * 3600, 1)
            else:
                return Response(status=HTTP_400_BAD_REQUEST)
        instance.save()
        return Response({"message": "操作成功", "success": True})


class LabelFullAPIView(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelsModelSerializer
